<template>
    <div class="app-container">
        <!-- 试卷的创建或者编辑 -->
        <el-form :model="formData" ref="formData" :rules="rules">
            <h1 style="text-align: center;">{{ formData.examName}} <span style="font-weight: normal; font-size: 25px;">(总分:{{formData.examTotal}})</span></h1>
            <h3 style="text-align: center;">学科：{{ formData.subjectName}}</h3>
            <div  v-if="isView" style="text-align: center; height: 40px;">
                    <p style="display: inline-block; margin-right: 80px;">考试时间：{{ formData.beginTime}}</p>  
                    <p style="display: inline-block;">时长：{{formData.examTime}} min</p>
            </div>
            <el-form-item label="考试时间" style="margin-left: 30%;" required v-if="!isView">
                <el-date-picker style="margin-right: 30px;" value-format="yyyy-MM-dd HH:mm:ss" @change="timeChange"
                    v-model="time"
                    type="datetimerange"
                    range-separator="至"
                    start-placeholder="开始日期"
                    end-placeholder="结束日期">
                </el-date-picker>
                <el-button type="primary" icon="el-icon-plus" @click="addQuestion" >新增试题</el-button>
            </el-form-item>
            <!-- 选择班级 -->
            <el-form-item label="所考班级" style="margin-left: 30%;" required v-if="isAdd">
                <el-select v-model="formData.classesIds" multiple filterable remote reserve-keyword
                    placeholder="请选择班级"
                    >
                    <el-option v-for="item in classesItems" :key="item.id" :value="item.id" :label="item.classesName"></el-option>
                </el-select>
            </el-form-item>
            <!-- 这边是题目展示列表 -->
            <el-card shadow="hover">
                <el-form-item :key="index" v-for="item,index in formData.questionItems" style="margin-left:50px;">
                    <el-row>
                        <el-col :span="20"> 
                            <questionItem :itemOrder="(index+1)" :questionItem="item" :getExamScore="getExamScore" :isView="isView"></questionItem>
                        </el-col>
                        <el-col :span="3" style="margin-left: 15px; margin-top: 45px;" v-if="!isView">
                            <el-button type="danger" @click="delQuestionItem(index)">删除</el-button>
                        </el-col>
                    </el-row>
                </el-form-item>
            </el-card>
            <el-form-item>
                <div class="operations">
                    <el-button type="primary" v-if="!isView" @click="submitForm">提交</el-button>
                    <el-button type="plain" @click="close" style="margin-right: 50px; float: right;">关闭</el-button>
                </div>
            </el-form-item>
        </el-form>
        <!-- 这边是弹窗的添加列表 -->
        <el-dialog :visible="dialogVisible " width="60%" :before-close="closeDialog">
            <el-form :model="queryParam" ref="queryParam" :inline="true">
                <el-form-item label="题目名称：" style="margin-left:40px" >
                    <el-input v-model="queryParam.questionName" placeholder="请输入题目名称"  clearable></el-input>
                </el-form-item>
                <el-form-item label="题型">
                    <el-select v-model="queryParam.questionType" clearable placeholder="请选择题型" >
                        <el-option
                        v-for="item in questionEnum"
                        :key="item.key"
                        :label="item.value"
                        :value="item.key">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item style="margin-left:20px">
                    <el-button type="primary" @click="search" icon="el-icon-search">查询</el-button>
                </el-form-item>
            </el-form>
            <el-table v-loading="listLoading" :data="tableData" border fit highlight-current-row style="width: 100%" ref="multipleTable"
                @selection-change="handleSelectionChange" >
                <el-table-column type="selection" width="55"></el-table-column>
                <el-table-column align="left" label="序号" type="index" width="50"></el-table-column>  
                <el-table-column prop="questionName"  align="left" label="试题名称"  />
                <el-table-column prop="questionType"  align="center" label="题目类型" width="120px" :formatter="questionTypeFormat" />
            </el-table>
            <el-row>
                <el-col :span="20" style="margin-top:15px" align="right">
                    <el-button type="success" @click="sureAdd">确认</el-button>
                </el-col>
                <el-col :span="3" style="margin-top:15px" align="right">
                    <el-button type="plain" @click="closeDialog">关闭</el-button>
                </el-col>
            </el-row>
            <el-pagination
                style="textAlign:center;margin-top: 20px;"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                :current-page="queryParam.pageIndex"
                :page-sizes="[10, 20, 30, 40]"
                :page-size="queryParam.pageSize"
                layout="total, sizes, prev, pager, next, jumper"
                :total="total">
            </el-pagination>
        </el-dialog>
    </div>
</template>

<script>
import {addPagesList} from '@/api/question/question'
import questionItem from './question/questionItem';
import {selectById,edit} from '@/api/exam/exam'
import {classesList} from '@/api/classes/classes'
export default {
    name:'ExamEdit',
    components:{questionItem},
    data(){
        return{
            // 试卷的数据
            formData:{
                id:null,
                examName:'',
                examTime:'',
                beginTime:null,
                endTime:null,
                subjectName:'',
                subjectId:null,
                examTotal:0,
                // 题目项
                questionItems:[],
                //班级列表
                classesIds:[],
            },
            time:[],
            rules:{
                time:{required: true, message:'请选择开考时间',trigger:'blur'}
            },
            // 是否是查看试卷
            isView: false,
            // 是否是新增试卷
            isAdd:false,
            // 弹窗的是否可见
            dialogVisible : false,
            // 弹窗相关数据
            queryParam:{
                pageIndex:1,
                pageSize:10,
                questionType:null,
                subjectId:null,
                questionName:''
            },
            mutilSelections:[],
            classesItems:[],
            total:0,
            tableData:[],
            listLoading:false,
            questionEnum:[
                {key:1,value:"单选题"},
                {key:2,value:"多选题"},
                {key:3,value:"判断题"},
                {key:4,value:"简答题"}
            ],
        }
    },
    mounted(){
        // 在此决定是查看试卷还是编辑或者新增试卷
        let id = this.$route.params.id;
        this.formData.id = id;
        this.formData.examName = this.$route.params.examName;
        let message = this.$route.params.message;
        if(!message){
            this.$router.push('/exam/index');
            return;
        }
        this.subNameAndId(this.$route.params.subject)
        if(id && parseInt(id) != 0){
            if(message == 'view'){
                this.isView = true;
                this.selectById(id);
            }else{
                this.selectById(id);
            }
        }else{
            this.getClassesList("_");
            this.isAdd = true;
        }
    },
    methods:{
        //时间选择器
        timeChange(val){
            console.log(val);
            if(new Date(val[0]) < new Date()){
                this.time = [];
                console.log(this.time);
                this.$message.info('开始时间不能低于当前时间，请重现选择');
            }
        },
        async getClassesList(val){
            let res = await classesList(val);
            this.classesItems = res.data;
        },
        // 拆分subjectId和subjectName
        subNameAndId(val){
            if(val){
                let index = val.indexOf('.');
                this.formData.subjectName = val.substring(index+1);
                this.formData.subjectId = val.substring(0,index);
                this.queryParam.subjectId = val.substring(0,index);
            }
        },
        dateFormat(){
            this.formData.beginTime = this.time[0];
            this.formData.endTime = this.time[1];
        },
        // 提交表单
        submitForm(){
                console.log(this.time);
                if(this.time.length <= 0){
                    this.$message.error("请选择开考时间");
                    return;
                }
                if( this.formData.classesIds != null && this.formData.classesIds.length <= 0){
                    this.$message.error("请选择考试的班级");
                    return;
                }
                if(this.formData.questionItems.length <= 0){
                    this.$message.error("考卷题目不能为空");
                    return;
                }
                    this.dateFormat();
                    edit(this.formData).then(resp =>{
                        this.formData.id = resp.data;
                        this.$message.success(resp.message);
                    });
                
        },
        close(){
            this.$router.push('/exam/index');
        },
        // 弹窗相关
        closeDialog(){
            this.dialogVisible = false;
        },
        addQuestion(){
            this.dialogVisible = true;
            this.search();
        },
        handleSelectionChange(val){
            this.mutilSelections = val;
        },
        sureAdd(){
            this.mutilSelections.forEach(el =>{
                this.formData.questionItems.push(el)
            })
            this.getExamScore(this.formData.questionItems);
            this.closeDialog();
        },
        delQuestionItem(id){
            this.formData.questionItems.splice(id,1);
            this.getExamScore();
        },
        // 获取总分
        getExamScore(){
            let score = 0;
            this.formData.questionItems.forEach(el=>{
                score += el.questionScore;
            })
            this.formData.examTotal = score;
        },
        search(){
            addPagesList(this.queryParam).then(resp=>{
                this.listLoading = true;
                this.tableData = resp.data.records;
                this.total = resp.data.total;
                this.listLoading = false;
            })
        },
        async selectById(val){
            let res = await selectById(val);
            this.formData = res.data;
            this.time.push(this.formData.beginTime);
            this.time.push(this.formData.endTime);
            this.queryParam.subjectId = this.formData.subjectId;
        },
        questionTypeFormat(row, column, cellValue, index){
            let name = '';
            this.questionEnum.forEach(i =>{
                if(i.key == cellValue){
                    name = i.value;
                    return;
                }
            })
            return name;
        },
        // 分页相关
        handleSizeChange(val) {
            this.queryParam.pageSize = val;
            this.search();
        },
        handleCurrentChange(val) {
            this.queryParam.pageIndex = val;
            this.search();
        },
    }
}
</script>

<style scoped>
    .operations{
        width: 400px;
        margin: 20px auto 0px;
    }
</style>